import { Button, Input, Space } from "antd";
import { useEffect, useState } from "react";

export interface ValidInputProps {
    value: unknown;
    defaultValue: unknown;
    validValue: (value: unknown) => string | null;
    onChange: (value: unknown) => void;
}

export default function ValidInput(props: ValidInputProps) {
    const [jsonStr, setJsonStr] = useState(JSON.stringify(props.value, null, 2));
    const [changed, setChanged] = useState(false);
    const [errStr, setErrStr] = useState<string | null>(null);

    useEffect(() => {
        try {
            const value = JSON.parse(jsonStr);
            const err = props.validValue(value);
            setErrStr(err);
        } catch (e) {
            setErrStr(`${e}`);
        }
    }, [jsonStr]);

    return (
        <div>
            <Input.TextArea rows={5} value={jsonStr} onChange={e => {
                e.stopPropagation();
                e.preventDefault();
                setJsonStr(e.target.value);
                setChanged(true);
            }} />
            {changed == true && (
                <div style={{ display: "flex", justifyContent: "flex-end", height: "50px" }}>
                    <Space>
                        <span style={{ color: "red" }}>{errStr ?? ""}</span>
                        <Button onClick={e => {
                            e.stopPropagation();
                            e.preventDefault();
                            setJsonStr(JSON.stringify(props.value, null, 2));
                            setChanged(false);
                        }}>取消</Button>
                        <Button type="primary" disabled={errStr != null} onClick={e => {
                            e.stopPropagation();
                            e.preventDefault();
                            const value = JSON.parse(jsonStr);
                            props.onChange(value);
                            setChanged(false);
                        }}>保存</Button>
                    </Space>
                </div>
            )}
        </div>
    )
}
